<template>
  <el-dialog v-model="visible" :title="`${paramsProps.title}`" :destroy-on-close="true" width="800px" draggable append-to-body>
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :model="paramsProps.row"
      @submit.enter.prevent="handleSubmit"
      class="form__label"
    >
      <el-row>
        <!-- <el-col :span="12">
          <el-form-item label="文件名" prop="fileName">
            <el-input v-model="paramsProps.row.fileName" placeholder="请填写文件名" clearable />
          </el-form-item>
        </el-col> -->
        <!-- <el-col :span="12">
          <el-form-item label="文件类型" prop="fileType">
            <el-select v-model="paramsProps.row.fileType" clearable placeholder="请选择文件类型">
              <el-option label="图片" value="image" />
              <el-option label="视频" value="video" />
              <el-option label="音频" value="audio" />
              <el-option label="文档" value="document" />
              <el-option label="压缩包" value="archive" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
        </el-col> -->
      </el-row>
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="文件大小" prop="fileSize">
            <el-input-number v-model="paramsProps.row.fileSize" :min="0" placeholder="请填写文件大小(字节)" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上传用户" prop="uploadUser">
            <el-input v-model="paramsProps.row.uploadUser" placeholder="请填写上传用户" clearable />
          </el-form-item>
        </el-col>
      </el-row> -->
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="paramsProps.row.status" clearable placeholder="请选择状态">
              <el-option label="待处理" value="PENDING" />
              <el-option label="处理中" value="PROCESSING" />
              <el-option label="成功" value="SUCCESS" />
              <el-option label="失败" value="FAILED" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否处理" prop="isProcessed">
            <el-radio-group v-model="paramsProps.row.isProcessed">
              <el-radio-button :label="true">是</el-radio-button>
              <el-radio-button :label="false">否</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row> -->
      <!-- <el-row>
        <el-col :span="12">
          <el-form-item label="上传时间" prop="uploadTime">
            <el-date-picker 
              v-model="paramsProps.row.uploadTime" 
              type="datetime" 
              placeholder="选择上传时间" 
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="处理时间" prop="processTime">
            <el-date-picker 
              v-model="paramsProps.row.processTime" 
              type="datetime" 
              placeholder="选择处理时间" 
              value-format="YYYY-MM-DD HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row> -->
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="文件路径" prop="filePath">
            <el-input v-model="paramsProps.row.filePath" placeholder="请填写文件路径" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="错误信息" prop="errorMessage">
            <el-input 
              v-model="paramsProps.row.errorMessage" 
              type="textarea" 
              :rows="3"
              placeholder="请填写错误信息（如有）" 
              clearable 
            />
          </el-form-item>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="24">
          <el-form-item label="车辆编号" prop="carNumber">
            <el-input 
              v-model="paramsProps.row.carNumber" 
              placeholder="请填写车辆编号" 
              clearable 
            />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input 
              v-model="paramsProps.row.remark" 
              type="textarea" 
              :rows="3"
              placeholder="请填写备注信息" 
              clearable 
            />
          </el-form-item>
        </el-col>
      </el-row> -->
      
      <!-- 文件URL预览（如果是图片） -->
      <el-row v-if="paramsProps.row.fileUrl && isImageFile(paramsProps.row.fileName, paramsProps.row.fileType, paramsProps.row.fileUrl)">
        <el-col :span="24">
          <el-form-item label="文件预览">
            <div class="image-preview-container">
              <AuthenticatedImage
                :src="paramsProps.row.fileUrl"
                :style="{
                  width: '200px',
                  height: '150px',
                  borderRadius: '6px'
                }"
                fit="cover"
              />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="visible = false"> 取消 </el-button>
      <el-button type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import { IS_PREVIEW } from '@/config';
import type { MonitorFileRecordInfo } from '@/api/types/datainfo/statisticsData';
import { useUserStore } from '@/stores/modules/user';
import AuthenticatedImage from './AuthenticatedImage.vue';

defineOptions({
  name: 'FileRecordEdit'
});

const userStore = useUserStore();

// 判断是否为图片文件
const isImageFile = (fileName: string, fileType?: string, fileUrl?: string) => {
  // 首先检查 fileType 是否包含具体的图片格式
  if (fileType) {
    const imageTypes = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg'];
    const fileTypeLower = fileType.toLowerCase();
    if (imageTypes.some(type => fileTypeLower.includes(type))) {
      return true;
    }
  }
  
  // 检查 fileUrl 中是否包含图片路径或扩展名
  if (fileUrl) {
    const imageUrlPatterns = [
      '/images/', '/img/', '/picture/', '/pic/',
      '.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'
    ];
    const urlLower = fileUrl.toLowerCase();
    if (imageUrlPatterns.some(pattern => urlLower.includes(pattern))) {
      return true;
    }
  }
  
  // 最后检查文件名扩展名
  if (fileName) {
    const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
    return imageExtensions.some(ext => fileName.toLowerCase().endsWith(ext));
  }
  
  return false;
};

// 表单验证规则
const rules = reactive({
  fileName: [{ required: true, message: '请填写文件名', trigger: 'blur' }],
  // fileType: [{ required: true, message: '请选择文件类型', trigger: 'change' }],
  // fileSize: [{ required: true, message: '请填写文件大小', trigger: 'blur' }],
  // uploadUser: [{ required: true, message: '请填写上传用户', trigger: 'blur' }],
  // status: [{ required: true, message: '请选择状态', trigger: 'change' }],
  // uploadTime: [{ required: true, message: '请选择上传时间', trigger: 'change' }],
  // filePath: [{ required: true, message: '请填写文件路径', trigger: 'blur' }],
  carNumber: [{ required: true, message: '请填写车辆编号', trigger: 'blur' }]
});

const visible = ref(false);
const paramsProps = ref<View.DefaultParams>({
  title: '',
  row: {} as MonitorFileRecordInfo,
  api: undefined,
  getTableList: undefined
});

// 接收父组件传过来的参数
const acceptParams = (params: View.DefaultParams) => {
  paramsProps.value = params;
  visible.value = true;
  
  // 确保数据类型正确
  if (paramsProps.value.row) {
    // 设置默认值
    if (!paramsProps.value.row.status) {
      paramsProps.value.row.status = 'PENDING';
    }
    if (paramsProps.value.row.isProcessed === undefined) {
      paramsProps.value.row.isProcessed = false;
    }
    if (!paramsProps.value.row.uploadTime) {
      paramsProps.value.row.uploadTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
    }
  }
};

// 提交数据（新增/编辑）
const ruleFormRef = ref();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async (valid: boolean) => {
    if (!valid) return;
    
    if (IS_PREVIEW) {
      return ElMessage.warning({ message: '预览环境，禁止编辑文件记录，请谅解！' });
    }
    
    try {
      const data = { ...paramsProps.value.row };
      
      // 数据处理：确保数据格式正确
      if (typeof data.fileSize === 'string') {
        data.fileSize = parseInt(data.fileSize) || 0;
      }
      if (data.isProcessed === undefined || data.isProcessed === null) {
        data.isProcessed = false;
      }
      
      await paramsProps.value.api!(data);
      ElMessage.success({ message: `${paramsProps.value.title}成功！` });
      paramsProps.value.getTableList!();
      visible.value = false;
    } catch (error) {
      console.error('File record edit error:', error);
      ElMessage.error('操作失败，请重试');
    }
  });
};

defineExpose({
  acceptParams
});
</script>

<style scoped lang="scss">
.form__label {
  :deep(.el-form-item__label) {
    font-weight: 500;
  }
}

.image-preview-container {
  display: flex;
  gap: 10px;
  
  .image-slot {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 100%;
    background-color: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 14px;
    
    .el-icon {
      font-size: 28px;
      margin-bottom: 8px;
    }
  }
}
</style>